package com.zerlings.gabeisfaker.ui

import android.Manifest
import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Intent
import android.didikee.donate.AlipayDonate
import android.didikee.donate.WeiXinDonate
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.view.*
import android.widget.PopupWindow
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.view.menu.MenuBuilder
import androidx.appcompat.view.menu.MenuPopupHelper
import androidx.appcompat.widget.PopupMenu
import androidx.core.view.GravityCompat.START
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import com.google.android.material.snackbar.Snackbar
import com.zerlings.gabeisfaker.R
import com.zerlings.gabeisfaker.databinding.ActivityMainBinding
import com.zerlings.gabeisfaker.ui.inventory.InventoryFragment
import com.zerlings.gabeisfaker.ui.main.CaseFragment
import com.zerlings.gabeisfaker.ui.simulator.SimulatorFragment
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.OnPermissionDenied
import permissions.dispatcher.RuntimePermissions
import java.io.File

@RuntimePermissions
class MainActivity : AppCompatActivity() {

    companion object {

        const val payCode = "FKX04508GKMZBVRPRF3U8A"

        const val downloadUrl = "https://www.coolapk.com/apk/com.zerlings.gabeisfaker"

        const val tradeUrl = "https://steamcommunity.com/tradeoffer/new/?partner=106454411&token=jSG5eL6U"

        const val LEVEL_RARE = 8

        const val LEVEL_EXTRAORDINARY = 7

        const val LEVEL_CONVERT = 6

        const val LEVEL_CLASSIFIED = 5

        const val LEVEL_RESTRICTED = 4

        const val LEVEL_MILSPEC = 3

        const val LEVEL_INDUSTRIAL = 2

        const val LEVEL_CONSUMER = 1

        const val LEVEL_ALL = 0
    }

    lateinit var  currentFragment: BaseFragment<*,*>

    val binding: ActivityMainBinding by lazy { DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main) }

    val viewModel: MainViewModel by lazy { ViewModelProvider(this).get(MainViewModel::class.java) }

    var snackbar: Snackbar? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN)
        /*载入价格数据*/
        if (!getFileStreamPath("allprices").exists()) {
            binding.progressBarLayout.visibility = View.VISIBLE
            viewModel.updatePrices()
            viewModel.priceJob?.invokeOnCompletion { binding.progressBarLayout.visibility = View.GONE }
        }else {
            viewModel.loadPrices()
        }
        /*侧滑菜单监听*/
        binding.navView.setNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.nav_inventory -> {
                    when (currentFragment) {
                        is CaseFragment -> Navigation.findNavController(this,R.id.host_fragment)
                                .navigate( R.id.action_case_fragment_to_inventory_fragment)
                        is SimulatorFragment -> Navigation.findNavController(this,R.id.host_fragment)
                                .navigate( R.id.action_simulator_fragment_to_inventory_fragment)
                        else -> {}
                    }
                    binding.drawerLayout.closeDrawers()
                }//库存
                R.id.nav_guide -> showGuidance()//指南
                R.id.nav_share -> shareApp()//分享
                R.id.nav_donate -> showPopupMenu()//捐赠
                R.id.nav_star -> starApp()//评价
                R.id.nav_update -> showUpdateInfo()//更新
                R.id.nav_quit -> finish()//退出
                R.id.all -> {
                    item.isChecked = true
                    (currentFragment as InventoryFragment).showSpecificList(LEVEL_ALL)
                }
                R.id.extraordinary -> {
                    item.isChecked = true
                    (currentFragment as InventoryFragment).showSpecificList(LEVEL_EXTRAORDINARY)
                }
                R.id.convert -> {
                    item.isChecked = true
                    (currentFragment as InventoryFragment).showSpecificList(LEVEL_CONVERT)
                }
                R.id.classified -> {
                    item.isChecked = true
                    (currentFragment as InventoryFragment).showSpecificList(LEVEL_CLASSIFIED)
                }
                R.id.restricted -> {
                    item.isChecked = true
                    (currentFragment as InventoryFragment).showSpecificList(LEVEL_RESTRICTED)
                }
                R.id.milspec -> {
                    item.isChecked = true
                    (currentFragment as InventoryFragment).showSpecificList(LEVEL_MILSPEC)
                }
                R.id.industrial -> {
                    item.isChecked = true
                    (currentFragment as InventoryFragment).showSpecificList(LEVEL_INDUSTRIAL)
                }
                R.id.consumer -> {
                    item.isChecked = true
                    (currentFragment as InventoryFragment).showSpecificList(LEVEL_CONSUMER)
                }
                else -> {}
            }
            false
        }
    }

    override fun onBackPressed() {
        when {
            currentFragment.onBackPressed() -> {}//fragment中的返回键处理
            binding.progressBarLayout.visibility == View.VISIBLE -> viewModel.priceJob?.cancel()
            snackbar?.isShown == true -> snackbar!!.dismiss()
            binding.drawerLayout.isDrawerOpen(START) -> binding.drawerLayout.closeDrawers()
            else -> super.onBackPressed()
        }
    }

    /**显示指南*/
    private fun showGuidance() {
        val guideView = LayoutInflater.from(this).inflate(R.layout.instruction, binding.drawerLayout,false)
        val guideWindow = PopupWindow(guideView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        guideWindow.isFocusable = true
        guideWindow.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        guideWindow.showAtLocation(binding.drawerLayout, Gravity.CENTER, 0, 0)
        binding.drawerLayout.closeDrawers()
    }

    /**分享*/
    private fun shareApp() {
        val sharedIntent = Intent()
        sharedIntent.action = Intent.ACTION_SEND
        sharedIntent.putExtra(Intent.EXTRA_SUBJECT, R.string.shared_text)
        sharedIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.shared_text) + downloadUrl)
        sharedIntent.type = "text/plain"
        startActivity(Intent.createChooser(sharedIntent, getString(R.string.shared_title)))
        binding.drawerLayout.closeDrawers()
    }

    /**评分*/
    private fun starApp() {
        val uri = Uri.parse("market://details?id=" + this.packageName)
        val starIntent = Intent(Intent.ACTION_VIEW, uri)
        try {
            starIntent.setClassName("com.coolapk.market", "com.coolapk.market.view.main.MainActivity")
            startActivity(starIntent)
        } catch (e: ActivityNotFoundException) {
            e.printStackTrace()
            Toast.makeText(this, R.string.coolapk_text, Toast.LENGTH_SHORT).show()
        } catch (e: SecurityException) {
            e.printStackTrace()
        }
        binding.drawerLayout.closeDrawers()
    }

    /**显示自定义PopupMenu */
    @SuppressLint("RestrictedApi")
    private fun showPopupMenu() {

        /*创建PopupMenu*/
        val navMenu = binding.navView.menu
        val navItem = navMenu.findItem(R.id.nav_donate)
        val donateMenu = PopupMenu(this, navItem.actionView)
        donateMenu.inflate(R.menu.donate_menu)
        /*自定义PopupMenu样式*/
        val popupHelper = MenuPopupHelper(this, donateMenu.menu as MenuBuilder, navItem.actionView)
        popupHelper.setForceShowIcon(true)
        /*设置监听器*/
        donateMenu.setOnMenuItemClickListener { menuItem ->
            when (menuItem.itemId) {
                R.id.alipay -> {
                    val hasInstalledAlipayClient = AlipayDonate.hasInstalledAlipayClient(this)
                    if (hasInstalledAlipayClient) {
                        AlipayDonate.startAlipayClient(this, payCode)
                    } else {
                        Toast.makeText(this, R.string.alipay_text, Toast.LENGTH_SHORT).show()
                    }
                    binding.drawerLayout.closeDrawers()
                }
                R.id.wechat -> {
                    donateViaWeChatWithPermissionCheck()
                    binding.drawerLayout.closeDrawers()
                }
                R.id.steam -> {
                    val intent = Intent()
                    intent.action = "android.intent.action.VIEW"
                    val uri = Uri.parse(tradeUrl)
                    intent.data = uri
                    startActivity(intent)
                    binding.drawerLayout.closeDrawers()
                }
                else -> {}
            }
            false
        }
        /*显示PopupMenu*/
        popupHelper.show()
    }

    /**更新提示*/
    private fun showUpdateInfo() {
        binding.drawerLayout.closeDrawers()
        snackbar = Snackbar.make(binding.navView, R.string.update_info, Snackbar.LENGTH_INDEFINITE)
        snackbar!!.setAction("OK") {
            binding.progressBarLayout.visibility = View.VISIBLE
            viewModel.updatePrices()
            viewModel.priceJob?.invokeOnCompletion { binding.progressBarLayout.visibility = View.GONE }
        }.show()
    }

    @NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    fun donateViaWeChat() {
        val hasInstalledWeCinClient = WeiXinDonate.hasInstalledWeiXinClient(this)
        if (hasInstalledWeCinClient) {
            snackbar = Snackbar.make(binding.navView, R.string.wechat_guide, Snackbar.LENGTH_INDEFINITE)
            snackbar!!.setAction("Go") {
                val weixinQrIs = resources.openRawResource(R.raw.donate_wechat)
                val qrPath = (Environment.getExternalStorageDirectory().absolutePath
                        + File.separator + "AndroidDonateSample" + File.separator + "donate_wechat.png")
                WeiXinDonate.saveDonateQrImage2SDCard(qrPath, BitmapFactory.decodeStream(weixinQrIs))
                WeiXinDonate.donateViaWeiXin(this, qrPath)
            }.show()
        } else {
            Toast.makeText(this, R.string.wechat_text, Toast.LENGTH_SHORT).show()
        }
    }

    @OnPermissionDenied(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    fun onStorageDenied() {
        Toast.makeText(this, R.string.wechat_permission, Toast.LENGTH_SHORT).show()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)
    }
}